/**
 * Created by yangsen on 2017/9/7.
 */
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {HttpClient} from "../../common/model/http-client";
import {Toast} from "../../common/model/util";
import {HomePage} from "../home/home";

@Component({
  selector: 'login',
  templateUrl: 'login.html'
})
export class LoginPage {
  mobile: string;
  verifyCode: string;
  verifyCodeText: string = '短信验证码';
  verifyCodeBtnDisable: boolean = false;

  constructor(public navCtrl: NavController, private http: HttpClient, private toast: Toast) {

  }

  checkForm(): boolean {
    let phonePattern: string = '^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$';
    let phoneReg = new RegExp(phonePattern);
    if (!this.mobile) {
      this.toast.show("请输入手机号");
      return false;
    } else if (!phoneReg.test(this.mobile)) {
      this.toast.show("请输入正确的手机号");
      return false;
    } else if (!this.verifyCode) {
      this.toast.show("请输入验证码");
      return false;
    }
    return true;
  }

  login() {
    if (this.checkForm()) {
      this.http.post('/login', {
        mobile: this.mobile,
        verifyCode: this.verifyCode
      }).subscribe(rsp => {
        if (rsp.isOk) {
          localStorage.setItem('token_key', rsp.data.key);
          this.navCtrl.push(HomePage);
        }
      });
    }
  }

  getVerifyCode() {
    this.http.get('/verifyCode/' + this.mobile).subscribe(rsp => {
        this.verifyCodeBtnDisable = true;
        this.countdownBtn(59);
    });
  }

  countdownBtn(second: number) {
    setTimeout(() => {
      this.verifyCodeText = second + '秒';
      if (second == 1) {
        this.verifyCodeText = '短信验证码';
        this.verifyCodeBtnDisable = false;
      } else {
        this.countdownBtn(--second);
      }
    }, 1000);

  }

}
